<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
let logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forInit = proxy.$Init || {}
const forFees = proxy.$Fees || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  typeId: proxy.$route.query.id || '',
  // ----
  amount: 0,
  // ----
  attr: '',
  val: 0,
  sponsorId: undefined,
  sponsorStatus: false,
  sponsorWork: false,
  // ----
  title: '',
  // ----
  key: '',
  head: [{
    name: '交费时间',
    key: 'time',
    style: { width: '30%' }
  }, {
    name: '交费金额（元）',
    key: 'amount',
    style: {}
  }, {
    name: '有效期至',
    key: 'date',
    style: { width: '30%' }
  }],
  // ----
  payId: 0,
  feeVal: 0,
  feeGive: 0,
  feeNum: 0,
  feeUnit: '',
  feeBtn: '',
  // ----
  callback: '',
  // ----
  forAdm: String(proxy.$Phone) === String(logUser.telphone) && proxy.$route.query.dealer_id
})
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const setInitData = () => {
  switch (String(user.typeId)) {
    case 'marketing': {
      user.callback = () => {
        const options = {
          type: 6,
          maxCount: 500,
          boxStyle: { width: '70%' },
          title: '欢迎使用【市场营销】系统',
          content: '费用：' + user.feeVal + '元/' + user.feeUnit,
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我来付费',
            class: 'xw-color-24',
            callback: (count) => {
              layerBox.value.close()
              // ----
              const lookGiveNum = forInit.look_num || 0
              const releaseGiveNum = forInit.release_num || 0
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payCount: count }
              const forExtend = { name: proxy.$route.name, opts: { forAttr: user.attr + ',dealer_views,opport_views', forVal: user.val + ',' + Number(count * lookGiveNum) + ',' + Number(count * releaseGiveNum), forType: 'shopFee' } }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
            }
          }]
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
    case 'marketRent': {
      user.callback = () => {
        const options = {
          type: 6,
          maxCount: 5,
          boxStyle: { width: '70%' },
          title: '入驻【万域商友会】批发市场',
          content: '费用：' + user.feeVal + '元/' + user.feeNum + user.feeUnit,
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我来付费',
            class: 'xw-color-24',
            callback: (count) => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payCount: count }
              const forExtend = { name: proxy.$route.name, opts: { forToast: '入驻【万域批发市场】付费成功', forAttr: user.attr, forVal: user.val } }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
            }
          }],
          callback: (count) => {
            layerBox.value.layer.content = '费用：' + Number(user.feeVal * count).toFixed(2) + '元/' + Number(user.feeNum * count) + user.feeUnit
          }
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
    case 'cloudRent': {
      user.callback = () => {
        const options = {
          type: 6,
          maxCount: 5,
          boxStyle: { width: '70%' },
          title: '入驻【万域商友会】云仓分销',
          content: '费用：' + user.feeVal + '元/' + user.feeNum + user.feeUnit,
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要分销',
            class: 'xw-color-24',
            callback: (count) => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payCount: count }
              const forExtend = { name: proxy.$route.name, opts: { forToast: '入驻【万域云仓分销】付费成功', forAttr: user.attr, forVal: user.val } }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
            }
          }],
          callback: (count) => {
            layerBox.value.layer.content = '费用：' + Number(user.feeVal * count).toFixed(2) + '元/' + Number(user.feeNum * count) + user.feeUnit
          }
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
    case 'lookFriends': {
      if (user.attr) user.key = user.attr
      user.head = [{
        name: '交费时间',
        key: 'time',
        style: { width: '30%' }
      }, {
        name: '交费金额（元）',
        key: 'amount',
        style: {}
      }, {
        name: '剩余次数',
        key: 'rest',
        style: { width: '30%' }
      }]
      // ----
      user.callback = () => {
        const options = {
          title: '购买【' + user.title + '】次数',
          content: '购买：' + user.feeVal + '元/' + user.feeGive + '条',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要购买',
            class: 'xw-color-24',
            callback: () => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payAttr: user.attr }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay) })
            }
          }]
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
    case 'publishBusi': {
      if (user.attr) user.key = user.attr
      user.head = [{
        name: '交费时间',
        key: 'time',
        style: { width: '30%' }
      }, {
        name: '交费金额（元）',
        key: 'amount',
        style: {}
      }, {
        name: '剩余次数',
        key: 'rest',
        style: { width: '30%' }
      }]
      // ----
      user.callback = () => {
        const options = {
          title: '购买【' + user.title + '】次数',
          content: '购买：' + user.feeVal + '元/' + user.feeGive + '条',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要购买',
            class: 'xw-color-24',
            callback: () => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payAttr: user.attr }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay) })
            }
          }]
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
    case 'sponsorPush': {
      // --获取赞助有效期--
      let workLine = []
      proxy.$Myfun.getJsonData(logUser.topupze, (resJson) => { workLine = resJson })
      let amountDateRetail = 0
      workLine.some((oneItem) => {
        if (String(oneItem.id) === String(user.typeId)) {
          oneItem.info.some((twoItem) => {
            if (String(twoItem.id) === String(user.payId)) amountDateRetail = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
          })
        }
      })
      const curDate = Date.parse(new Date())
      user.sponsorWork = Number(amountDateRetail) >= Number(curDate)
      // --获取是否曾经赞助--
      setPublicInfo({
        type: 'get',
        url: 'meeting-organiser/index',
        data: {
          params: { 'MeetingOrganiserSearch[dealer_id]': logUser.id }
        }
      }, (res) => {
        if (Number(res.items.length) > 0) {
          user.sponsorId = res.items[0].id
          user.sponsorStatus = Number(res.items[0].status) === 2
        }
      })
      // ----
      user.callback = () => {
        const options = {
          type: 6,
          maxCount: 5,
          boxStyle: { width: '70%' },
          title: '你给我赞助，我给你推广',
          content: '费用：' + user.feeVal + '元/' + user.feeNum + user.feeUnit,
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要赞助',
            class: 'xw-color-24',
            callback: (count) => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.typeId, regType: 'jobs', payId: user.payId, payIdKey: 'jobs_id', payCount: count }
              let forExtend = { name: proxy.$route.name }
              if (!user.sponsorWork && user.sponsorStatus) forExtend = { name: proxy.$route.name, opts: { forAttr: user.attr, forVal: user.val, forId: user.sponsorId } }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
            }
          }],
          callback: (count) => {
            layerBox.value.layer.content = '费用：' + Number(user.feeVal * count).toFixed(2) + '元/' + Number(user.feeNum * count) + user.feeUnit
          }
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
  }
}
// ----
const setPublicInfo = async (item, callback) => {
  await proxy.$http[item.type](item.url, item.data).then((res) => {
    if (res) callback && callback(res)
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const setPayState = async () => {
  if (proxy.$route.query.forToast) proxy.$Myfun.forToast(layer.value, 'open', proxy.$route.query.forToast)
  // ----
  if (proxy.$route.query.forId && proxy.$route.query.forAttr && proxy.$route.query.forVal) {
    const forData = {
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
    const attrArr = proxy.$route.query.forAttr.split(',')
    const valArr = proxy.$route.query.forVal.split(',')
    attrArr.forEach((item, index) => {
      forData[item] = Number(valArr[index])
    })
    await setPublicInfo({
      type: 'patch',
      url: 'meeting-organiser/update?id=' + proxy.$route.query.forId,
      data: forData
    }, (res) => {
      // --清空参数--
      proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.name)
    })
  }
  // ----
  if (proxy.$route.query.forAttr && proxy.$route.query.forVal) {
    const forData = {
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
    const attrArr = proxy.$route.query.forAttr.split(',')
    const valArr = proxy.$route.query.forVal.split(',')
    attrArr.forEach((item, index) => {
      forData[item] = Number(valArr[index])
    })
    await setPublicInfo({
      type: 'patch',
      url: 'dealer/update?id=' + logUser.id,
      data: forData
    }, (res) => {
      // --清空参数--
      proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.name)
    })
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  forFees.some((item) => {
    if (String(item.id) === String(user.typeId)) {
      user.title = proxy.$Myfun.setText(item.name)
      user.feeBtn = proxy.$Myfun.setText(item.btnTxt)
      user.attr = proxy.$Myfun.setText(item.attr)
      user.val = item.val
      // ----
      user.feeVal = Number(item.amount)
      user.feeGive = item.give
      user.feeNum = Number(item.num)
      user.feeUnit = item.typeText
    }
  })
  // ----
  if (proxy.$route.query.dealer_id) {
    await proxy.$http.get('dealer/index', {
      params: { 'DealerSearch[id]': proxy.$route.query.dealer_id }
    }).then((res) => { logUser = res.items[0] }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  await setInitData()
  // --计算累计交费--
  const forAccount = {
    params: {
      'JobsAccountSearch[pay_type]': user.typeId,
      'JobsAccountSearch[status]': '充值成功',
      'JobsAccountSearch[dealer_id]': logUser.id,
      // ----
      page: 1,
      PageSize: 1000000000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('jobs-account/index', forAccount)
  ]).then(proxy.$Axios.spread((account) => {
    let forAccount = 0
    account.items.forEach((item) => { forAccount += Number(item.amount) })
    user.amount = forAccount.toFixed(2)
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  await setPayState()
  // --设置网页title--
  const forTitle = '【' + user.title + '】' + document.title
  setAppTitle(forTitle)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 20 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 20,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'jobs-account/index',
    forData: {
      params: {
        'JobsAccountSearch[pay_type]': user.typeId,
        'JobsAccountSearch[status]': '充值成功',
        'JobsAccountSearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const forRest = (user.key && Number(user.key.length) > 0 && Number(i) === 0) ? logUser[user.key] : 0
    // ----
    newItems.push({
      id: item.id,
      dealer_id: item.dealer_id,
      time: proxy.$Myfun.getDateShort(item.finished_at),
      amount: item.amount,
      date: proxy.$Myfun.getDateShort(item.deadline),
      rest: forRest
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type) => {
  switch (Number(type)) {
    case 1: {
      user.callback && user.callback()
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-bgCL-11 xw-flex xw-flex-align xw-flex-justify">
        <div class="TOP-title">累计交费：{{user.amount}}元</div>
        <div class="TOP-submit xw-radius-3 xw-WhiteRed xw-act" @click="getAuditFun(1)" v-if="!user.forAdm">{{user.feeBtn}}</div>
      </div>
      <div class="list-box">
        <ul>
          <li>
            <div v-for="(item, index) in user.head" :style="item.style">{{item.name}}</div>
          </li>
        </ul>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <div class="list-cash" ref="dataList">
          <ul class="xw-bg-white">
            <li v-for="(item, index) in items">
              <div :style="user.head[0].style">{{item[user.head[0].key]}}</div>
              <div :style="user.head[1].style">{{item[user.head[1].key]}}</div>
              <div :style="user.head[2].style">{{item[user.head[2].key]}}</div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-box ul { display: table; width: 100%; table-layout: fixed; border-collapse: collapse; }
.list-box ul li { display: table-row; border-style: solid; border-color: #d7d7d7; border-width: 0 0 1px; }
.list-box ul li div { display: table-cell; padding: 0.5rem; line-height: 2.5rem; vertical-align: middle; word-wrap: break-word; word-break: break-all; border-style: solid; border-color: #d7d7d7; border-width: 0 0 0 1px; text-align: center; font-weight: bold; }
.list-box ul li div:nth-of-type(1) { border-width: 0; }

/* ---- */
.list-cash ul { display: table; width: 100%; table-layout: fixed; border-collapse: collapse; }
.list-cash ul li { display: table-row; border-style: solid; border-color: #d7d7d7; border-width: 0 0 1px; }
.list-cash ul li div { display: table-cell; padding: 0.5rem; line-height: 2.5rem; font-size: 1.3rem; vertical-align: middle; word-wrap: break-word; word-break: break-all; border-style: solid; border-color: #d7d7d7; border-width: 0 0 0 1px; text-align: center; }
.list-cash ul li div:nth-of-type(1) { border-width: 0; }
</style>
